/**
 * Copyright (c) 2017-2018,Retire 吴益峰 (372310383@qq.com).
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.jplus.admin.service.impl;

import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.Page;
import io.jboot.aop.annotation.Bean;
import io.jboot.core.cache.annotation.Cacheable;
import io.jboot.core.rpc.annotation.JbootrpcService;
import io.jboot.db.model.Column;
import io.jboot.db.model.Columns;
import io.jboot.service.JbootServiceBase;
import io.jplus.Consts;
import io.jplus.admin.model.User;
import io.jplus.admin.service.UserService;
import io.jplus.utils.EncryptUtils;

import javax.inject.Singleton;
import java.util.List;

@Singleton
@Bean
@JbootrpcService
public class UserServiceImpl extends JbootServiceBase<User> implements UserService {

    @Override
    public List<User> findAll() {
        return DAO.findAll();
    }

    @Override
    public Ret doLogin(String account, String password) {
        User user = findByAccount(account);

        if (user == null) {
            return Ret.fail(Consts.RET_MSG, "没有该用户").set("code", Consts.LOGIN_FAIL_USER);
        }

        String uPwd = EncryptUtils.encryptPassword(password, user.getSalt());
        if (!uPwd.equals(user.getPassword())) {
            return Ret.fail(Consts.RET_MSG, "密码错误").set("code", Consts.LOGIN_FAIL_PWD);
        }

        return Ret.ok("user", user);

    }

    @Cacheable(name = "user", key = "#(account)")
    @Override
    public User findByAccount(String account) {
        Columns columns = Columns.create();
        columns.eq("account",account);
        return DAO.findFirstByColumns(columns);
    }

    @Override
    public Page<User> paginateByColumns(int page, int size, List<Column> columns, String orderBy) {
        return DAO.paginateByColumns(page, size, columns, orderBy);
    }

    @Override
    public List<User> findListByColumns(List<Column> columns) {
        return DAO.findListByColumns(columns);
    }

}
